package com.stx.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;

public class JwtUtils {

    private static String signKey = "itheima";
    private static int expirationDays = 7;

    /**
     * 生成JWT令牌
     *
     * @param claims JWT第二部分负载 payload 中存储的内容
     * @return
     */
    public String generateJwt(Map<String, Object> claims) {
        return JWT.create()
                .withExpiresAt(getExpiresAt())
                .withPayload(claims)
                .sign(Algorithm.HMAC256(signKey));
    }

    public DecodedJWT verify(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(signKey)).build();
        return verifier.verify(token);
    }

    public Long getLongValue(DecodedJWT jwt, String key) {
        Claim claim = jwt.getClaim(key);
        return claim.asLong();
    }

    public Integer getIntValue(DecodedJWT jwt, String key) {
        Claim claim = jwt.getClaim(key);
        return claim.asInt();
    }

    public String getStringValue(DecodedJWT jwt, String key) {
        Claim claim = jwt.getClaim(key);
        return claim.asString();
    }

    public Instant getExpiresAt() {

        return Instant.now().plus(expirationDays, ChronoUnit.DAYS);
    }
}
